<template>
  <div class="user-container">
    <!-- 头部的面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 一个卡片区域 -->
    <el-card class="box-card">
      <!-- 头部搜索、添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="userParams.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 展示用户列表区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="stateChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="initEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="small" @click="setRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="userParams.pagenum" :page-sizes="[2, 5, 10]" :page-size="userParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="totalUsers"> </el-pagination>
    </el-card>

    <!-- 添加用户弹出对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
      <!-- 表单区域 -->
      <el-form :model="addUserForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" size="small"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="resetEditForm">
      <!-- 表单区域 -->
      <el-form :model="editUserForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹出对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @closed="closeSetRoleDialog">
      当前用户:<el-input v-model="userinfo.username" disabled></el-input> 当前角色：<el-input v-model="userinfo.role_name" disabled></el-input>
      <div style="margin-top:10px">
        分配新角色:
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUserList()
  },
  data() {
    // 自定义验证手机号 rule是验证规则，value是要验证的值，callback为回调函数
    var checkMobile = (rule, value, callback) => {
      // 手机号的正则表达式
      const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    // 自定义验证邮箱
    var checkEmail = (rule, value, callback) => {
      // 手机号的正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/

      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱号'))
    }

    return {
      userParams: {
        query: '',
        // 第几页
        pagenum: 1,
        // 每页多少条
        pagesize: 2
      },
      // 总用户数量
      totalUsers: 0,
      // 存放user
      userList: [],
      // user的id
      userId: '',
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户form表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单验证
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 修改用户form表单
      editUserForm: {},
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 保存用户信息
      userinfo: {},
      // 保存角色信息
      rolesList: [],
      // 保存已选中角色的id值
      selectRoleId: ''
    }
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.userParams })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败!')
      this.totalUsers = res.data.total
      this.userList = res.data.users
      // console.log(this.userList)
    },
    // 监听pagesize更新事件
    handleSizeChange(newPagesize) {
      this.userParams.pagesize = newPagesize
      // 重新发起请求
      this.getUserList()
    },
    // 监听页码值更新事件
    handleCurrentChange(pagenum) {
      this.userParams.pagenum = pagenum
      this.getUserList()
    },
    // 用户状态更新按钮响应函数
    async stateChange(userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        // 如果不成功 回复原来的状态
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改用户状态失败!')
      }
      this.$message.success('修改用户状态成功！')
    },
    // 关闭添加用户对话框时重置表单
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return // 验证失败
        // 发起添加用户请求
        const { data: res } = await this.$http.post('users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        // 添加用户列表成功
        this.$message.success('添加成功')
        // 添加成功就关闭对话框
        this.addDialogVisible = false
        // 重新获取用户列表
        this.getUserList()
      })
    },
    // 点击修改显示对话框响应事件
    async initEditDialog(id) {
      console.log(id)
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.editUserForm = res.data
    },
    // 关闭修改用户对话框时重置表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败！')
        // 关闭修改对话框
        this.editDialogVisible = false
        // 提示修改成功
        this.$message.success('修改成功!')
        // 重新更新列表
        this.getUserList()
      })
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm('是否永久删除该用户信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async val => {
          console.log(id)
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 弹出分配角色对话框
    async setRoleDialog(userinfo) {
      // 获取用户信息
      this.userinfo = userinfo
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 分配角色对话框确认按钮响应事件
    async editRole() {
      console.log(this.userinfo.id)
      console.log(this.selectRoleId)
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败!')
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听关闭分配角色对话框按钮事件
    closeSetRoleDialog() {
      this.selectRoleId = ''
      this.userinfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 15px;
}
</style>
